'use strict';

const Controller = require('egg').Controller;
const Sequelize = require('sequelize');
let temp_obj = {};
class ClassfigyController extends Controller {
  /**
       * @api {Post} /api/classify 添加分类(管理台)
       * @apiGroup 商品分类
       * @apiParam {String}  authorization ⚡登录成功后的token值
       * @apiParam {String}  name       ⚡ 分类名称
       * @apiParam {String}  parent_id  ⚡ 父类ID  （默认0）
       * @apiParam {String}  sort        排序,从小到大
       * @apiParam {String}  path       分类路径
       * @apiParamExample 参数模板
       {
         "authorization":"123456789abcdefqwerxyzbluejgoods",
         "name": "男装",
         "authorization":"123456789abcdefqwerxyzbluejgoods"
        }
       * @apiSuccessExample 成功返回
       * {
       *    "msg":'添加成功'
       * }
       *
       * @apiErrorExample 错误返回
       * {
       *  "msg":"添加失败"
       * }
       *
       */
  async create() {
    const { ctx } = this;
    const { Classify } = this.app.model.Tables.Shop;
    const dataObj = ctx.request.body;
    console.log(dataObj);
    try {
      dataObj.sort = dataObj.sort || 999;
      dataObj.user_id = ctx.adminInfo.id;
      dataObj.project_id = ctx.adminInfo.project_id;

      // 判断当前项目与用户id是存在相同的名字（同级目录的前提下），没有则创建
      const result = await Classify.findOrCreate({
        where: {
          name: dataObj.name,
          user_id: dataObj.user_id,
          project_id: dataObj.project_id,
          parent_id: dataObj.parent_id,
        },
        defaults: dataObj,
      });
      ctx.body = result[0]._options.isNewRecord
        ? ctx.response.success('添加成功')
        : ctx.response.error(
            result,
            '添加失败"' + dataObj.name + '"名字有相同'
          );
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }
  // 获取所有商品分类信息
  /**
       * @api {Get} /api/classify 获取所有商品分类信息
       * @apiGroup 商品分类
       * @apiParam {String}  authorization        ⚡登录成功后的token值
       * @apiParam {INTEGER}  project_id      项目id
       * @apiParam {String}  page             第几页
       * @apiParam {String}  limit            每页多少条数据
       * @apiParam {String}  status          分类状态(0停用，1可用，2删除；不传默认显示全部)
       * @apiParam {String}  id               分类id（筛选用）
       * @apiParam {String}  name             分类名称（搜索用）
       * @apiParamExample 参数模板
        {}
       * @apiSuccessExample  成功返回
       {
          "msg": "成功操作",
          "result": [
              {
                  "id": 1,
                  "name": "男装",
                  "sort": 999,
                  "parent_id": 0,
                  "project_id": 3,
                  "status": "0",
                  "thumb_url": null,
                  "createdAt": "2020-07-31T09:22:57.000Z",
                  "updatedAt": "2020-07-31T09:22:57.000Z"
              },
              {
                  "id": 4,
                  "name": "女装",
                  "sort": 999,
                  "parent_id": 0,
                  "project_id": 3,
                  "status": "0",
                  "thumb_url": null,
                  "createdAt": "2020-07-31T09:25:58.000Z",
                  "updatedAt": "2020-07-31T09:25:58.000Z"
              },
              {
                  "id": 6,
                  "name": "童装",
                  "sort": 999,
                  "parent_id": 0,
                  "project_id": 3,
                  "status": "1",
                  "thumb_url": null,
                  "createdAt": "2020-07-31T09:27:57.000Z",
                  "updatedAt": "2020-07-31T09:27:57.000Z"
              },
          ]
      }
       * @apiErrorExample  错误返回
       * {
       *   "msg": "获得所有商品分类信息失败"
       * }
       */

  async index() {
    const { ctx } = this;
    try {
      const Op = Sequelize.Op;
      const { Classify } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      const limit = parseInt(query.limit) || 10;
      // 页数
      const offset = parseInt(query.offset) || 0;
      // 页数 * 每页个数
      // const offset = limit * (page - 1);
      const str_status = this.ctx.query.status; ///获取前端传过来的状态码
      //对状态码进行处理
      let arr_status;
      if (str_status == undefined || str_status == '') {
        arr_status = null;
        //如果前端没有传或者传递一个空的status
        //就默认显示所有状态的分类
      } else {
        arr_status = str_status.split(',');
        //前端传了状态码，只显示对应状态码的分类
      }
      const where = {
        status: arr_status || [0, 1, 2],
      };
      query.id && (where.id = query.id);
      query.name && (where.name = { [Op.like]: `%${query.name}%` });
      where.project_id = query.project_id || this.ctx.adminInfo.project_id;
      const result = await Classify.findAll({
        limit,
        offset,
        where,
      });
      if (result) {
        const data = JSON.parse(JSON.stringify(result));
        temp_obj = {};
        data.forEach((val) => {
          val.value = val.id;
          val.key = val.id;
          val.label = val.name;
          temp_obj[val.parent_id]
            ? temp_obj[val.parent_id].push(val)
            : (temp_obj[val.parent_id] = [val]);
        });
        ctx.body = ctx.response.success(this.melon());
      } else {
        ctx.body = ctx.response.error('获得所有商品分类信息失败');
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }

  // 获取每个分类的商品信息
  /**
       * @api {Get} /api/classify/classifyGoods 获取每个分类的商品信息
       * @apiGroup 商品分类
       * @apiParam {INTEGER}  project_id      项目id(不传时默认使用后台设置的项目id)
       * @apiParamExample 参数模板
       {}
       * @apiSuccessExample  成功返回
      {
          "msg": "成功操作",
          "result": [
              {
                  "id": 42,
                  "user_id": 7,
                  "project_id": 3,
                  "name": "手机",
                  "sort": "999",
                  "parent_id": 0,
                  "status": "1",
                  "thumb_url": null,
                  "path": "0",
                  "createdAt": "2020-09-16T03:13:29.000Z",
                  "updatedAt": "2020-09-16T03:13:29.000Z",
                  "s_goods": [
                      {
                          "id": 14,
                          "name": "Redmi K30 至尊纪念版",
                          "s_photos": [
                              {
                                  "id": 108,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327442119-dea0df353fcc369128b6bd7ae161bec5.jpg"
                              }
                          ]
                      },
                      {
                          "id": 15,
                          "name": "小米10至尊纪念版",
                          "s_photos": [
                              {
                                  "id": 107,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327427710-d6b57d87409f1ccbde695d05e2c47e78.webp"
                              }
                          ]
                      }
                  ],
                  "value": 42,
                  "key": 42,
                  "label": "手机"
              },
              {
                  "id": 43,
                  "user_id": 7,
                  "project_id": 3,
                  "name": "电视",
                  "sort": "999",
                  "parent_id": 0,
                  "status": "1",
                  "thumb_url": null,
                  "path": "0",
                  "createdAt": "2020-09-16T03:13:50.000Z",
                  "updatedAt": "2020-09-16T03:13:50.000Z",
                  "s_goods": [
                      {
                          "id": 16,
                          "name": "小米透明电视",
                          "s_photos": [
                              {
                                  "id": 104,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327393397-09d465165f5e370ac90b11897148861c.jpg"
                              },
                              {
                                  "id": 105,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327397808-a29082d2e55cf7e8e9ebdb61b6aa5401.jpg"
                              },
                              {
                                  "id": 106,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327402909-66fe4fc9bd4eb914c05e7e0ccae8820f.jpg"
                              }
                          ]
                      }
                  ],
                  "value": 43,
                  "key": 43,
                  "label": "电视"
              },
              {
                  "id": 44,
                  "user_id": 7,
                  "project_id": 3,
                  "name": "笔记本",
                  "sort": "999",
                  "parent_id": 0,
                  "status": "1",
                  "thumb_url": null,
                  "path": "0",
                  "createdAt": "2020-09-16T03:14:02.000Z",
                  "updatedAt": "2020-09-16T03:14:02.000Z",
                  "s_goods": [
                      {
                          "id": 17,
                          "name": " Redmi G 游戏本",
                          "s_photos": [
                              {
                                  "id": 103,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327155659-b5cf5e20eda87a3ff77e4a2d33828947.jpg"
                              }
                          ]
                      }
                  ],
                  "value": 44,
                  "key": 44,
                  "label": "笔记本"
              },
              {
                  "id": 45,
                  "user_id": 7,
                  "project_id": 3,
                  "name": "家电",
                  "sort": "999",
                  "parent_id": 0,
                  "status": "1",
                  "thumb_url": null,
                  "path": "0",
                  "createdAt": "2020-09-16T03:14:24.000Z",
                  "updatedAt": "2020-09-16T03:14:24.000Z",
                  "s_goods": [
                      {
                          "id": 18,
                          "name": "米家互联网十字四门冰箱 486L",
                          "s_photos": []
                      },
                      {
                          "id": 19,
                          "name": "米家微波炉",
                          "s_photos": []
                      },
                      {
                          "id": 22,
                          "name": "米家微波炉",
                          "s_photos": [
                              {
                                  "id": 101,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327059846-c300ae434343b009621c000ef85bc849.jpg"
                              },
                              {
                                  "id": 102,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600327064087-f8257b2133997d801c1f9af7ae41d66a.jpg"
                              }
                          ]
                      }
                  ],
                  "value": 45,
                  "key": 45,
                  "label": "家电"
              },
              {
                  "id": 46,
                  "user_id": 7,
                  "project_id": 3,
                  "name": "出行穿戴",
                  "sort": "999",
                  "parent_id": 0,
                  "status": "1",
                  "thumb_url": null,
                  "path": "0",
                  "createdAt": "2020-09-16T03:14:28.000Z",
                  "updatedAt": "2020-09-16T03:14:28.000Z",
                  "s_goods": [
                      {
                          "id": 23,
                          "name": "小米手环5 NFC版",
                          "s_photos": [
                              {
                                  "id": 125,
                                  "path": "http://shops-1251395798.cos.ap-nanjing.myqcloud.com/1600342120209-cc6cbcc3c987ea01bf1ea1ea9a58d0c2.jpg"
                              }
                          ]
                      }
                  ],
                  "value": 46,
                  "key": 46,
                  "label": "出行穿戴"
              },
          ]
      }
       * @apiErrorExample  错误返回
       * {
       *   "msg": "获得每个分类的商品信息失败"
       * }
       */

  async classifyGoods() {
    const { ctx } = this;
    try {
      const Op = Sequelize.Op;
      const { Classify, Goods, GoodsPhoto } = this.app.model.Tables.Shop;
      const where = {
        status: {
          [Op.ne]: '2',
        },
      };
      const query = this.ctx.query;
      where.project_id =
        query.project_id || (ctx.adminInfo && ctx.adminInfo.project_id);
      const result = await Classify.findAll({
        where,
        include: [
          {
            // 需要的字段
            attributes: ['id', 'name', 'price', 'sale_price', 'sold_num'],
            // 链接的表
            model: Goods,
            include: [
              {
                // 需要的字段
                attributes: ['id', 'path'],
                model: GoodsPhoto,
              },
            ],
          },
        ],
      });
      if (result) {
        const data = JSON.parse(JSON.stringify(result));
        temp_obj = {};
        data.forEach((val) => {
          val.value = val.id;
          val.key = val.id;
          val.label = val.name;
          temp_obj[val.parent_id]
            ? temp_obj[val.parent_id].push(val)
            : (temp_obj[val.parent_id] = [val]);
        });
        ctx.body = ctx.response.success(this.melon());
      } else {
        ctx.body = ctx.response.error('获得所有商品分类信息失败');
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }

  melon(parent_id = 0) {
    if (temp_obj.hasOwnProperty(parent_id)) {
      const temp_arr = temp_obj[parent_id];
      temp_arr.forEach((val, index) => {
        const second_arr = this.melon(val.id);
        second_arr.length && (temp_arr[index].children = second_arr);
      });
      return temp_arr;
    }
    return [];
  }

  // 获取单个商品分类信息
  /**
       * @api {Get} /api/classify/:id  获取单个商品分类信息
       * @apiGroup 商品分类
       * @apiParamExample 参数模板
       {}
       * @apiSuccessExample  成功返回
      {
          "msg": "成功操作",
          "result": {
              "id": 4,
              "name": "女装",
              "sort": 999,
              "parent_id": 0,
              "project_id": 3,
              "status": "0",
              "thumb_url": null,
              "createdAt": "2020-07-31T09:25:58.000Z",
              "updatedAt": "2020-07-31T09:25:58.000Z"
          }
      }
       * @apiErrorExample  错误返回
       * {
       *   "msg": "找不到该商品分类信息"
       * }
       */

  async show() {
    const { ctx } = this;
    const id = ctx.params.id;
    const data = ctx.query;
    const checkRes = new this.ctx.helper.checkData(this, 'project_id')
      .checkDataRes;

    try {
      if (checkRes) {
        const { Classify, GoodsPhoto } = this.app.model.Tables.Shop;
        const result = await Classify.findOne({
          project_id: data.project_id,
          where: {
            id,
          },
        });
        if (result) {
          ctx.body = ctx.response.success(result);
        } else {
          ctx.body = ctx.response.error('找不到该商品分类信息');
        }
      }
    } catch (error) {
      ctx.body = ctx.response.error(error.message);
    }
  }
  // 更新商品分类信息
  /**
       * @api {put} /api/classify/:id 更新商品分类信息
       * @apiGroup 商品分类
       * @apiParam {String}  name       // 分类名称    （必填）
       * @apiParam {String}  parent_id  // 父类ID  （默认0）
       * @apiParam {String}  sort       // 排序,从小到大
       * @apiParam {String}  status     // 状态，0停用,1可用,2删除 (默认1)
       * @apiParam {String}  thumb_url   // 缩略图路径
       * @apiParamExample 参数模板
       {}
       * @apiSuccessExample  成功返回
       {
          "msg": "成功操作",
          "result": {
              "id": 4,
              "name": "女装",
              "sort": 999,
              "parent_id": 0,
              "project_id": 3,
              "status": "0",
              "thumb_url": null,
              "createdAt": "2020-07-31T09:25:58.000Z",
              "updatedAt": "2020-07-31T09:25:58.000Z"
          }
      }
       * @apiErrorExample  错误返回
       * {
       *   "msg": "找不到该商品分类信息"
       * }
       */

  async update() {
    const { ctx } = this;
    const dataObj = ctx.request.body;
    dataObj.status && dataObj.status.toString();
    // (dataObj.status) == (dataObj.status.toString());
    // let data = [];
    // (dataObj.name) && (data.push('name'))
    // (dataObj.s_goods) && (data.push('s_goods'))

    if (
      new ctx.helper.checkData(this, 'id', 'name', 'parent_id').checkDataRes
    ) {
      const id = ctx.params.id;

      try {
        const { Classify } = this.app.model.Tables.Shop;

        const resultAdmin = await Classify.findByPk(id);

        if (resultAdmin && resultAdmin.dataValues) {
          // console.log(dataObj.parent_id,'-----------------');
          const result = await resultAdmin.update(dataObj, {
            where: {
              parent_id: dataObj.parent_id,
              name: dataObj.name,
            },
          });
          ctx.body = ctx.response.success(result.dataValues);
        } else {
          ctx.body = ctx.response.error('找不到该商品分类信息');
        }
      } catch (error) {
        ctx.body = ctx.response.error(error.message);
      }
    }
  }

  /**
       * @api {delete} /api/classify/:id 删除商品分类id
       * @apiGroup 商品分类
       * @apiParamExample 参数模板
       {}
       * @apiSuccessExample 成功返回
       * {
       *    "msg":'删除成功'
       * }
       *
       * @apiErrorExample 错误返回
       * {
       *  "msg":"删除失败"
       * }
       *
       */

  async destroy() {
    const { ctx } = this;
    const id = ctx.params.id;
    try {
      const { ctx } = this;
      const { Classify, Goods } = this.app.model.Tables.Shop;
      const resultGoods = await Goods.findAll({
        where: {
          classify_id: id,
        },
      });
      if (resultGoods.length == 0) {
        const result = await Classify.destroy({
          where: {
            id,
            user_id: this.ctx.adminInfo.id,
          },
        });
        ctx.body =
          result > 0
            ? ctx.response.success('删除成功')
            : ctx.response.error(result, '删除失败');
      } else {
        ctx.body = ctx.response.error(
          `分类id为 ${id} 的分类下还有商品，请勿删除`
        );
      }
    } catch (error) {
      ctx.body = this.ctx.response.error(error.message);
    }
  }
}

module.exports = ClassfigyController;
